import React, {Component} from "react";
import { Card, Input, Form, message, Button } from 'antd'

// 引入编辑器组件
import BraftEditor from 'braft-editor'
// 引入编辑器样式
import 'braft-editor/dist/index.css'
import 'braft-editor/dist/output.css'


import { MedicalDetailsStory, updateMedicalStory,addMedicalStory } from '../../api/medical'
import {upload} from '../../api/scene'
class MedicalDetail extends Component {
    myRef = React.createRef()
    state = {
        id: '',
        info: {
          name: '' ,
          likes: '',
          content: '',
          reading: ''
        },
        editContent: BraftEditor.createEditorState(null),
        Look: true
    }
    componentDidMount () {
        const id = this.props.location.query ? this.props.location.query.id :  window.sessionStorage.getItem('id')
        if (id) {
            window.sessionStorage.setItem('id', id)
            const Look = window.sessionStorage.getItem('Look') || true
            this.setState({id, Look}, () => {
             this.getDetails()
         })
        } else {
            this.setState({Look: false})
        }
     }

     componentWillUnmount () {
       window.sessionStorage.setItem('id', '')
       window.sessionStorage.setItem('Look', true)
     }

     // 获取详情
     getDetails = async () => {
        const res = await MedicalDetailsStory({ storyId: this.state.id})
        const {createTime, ...info} = res.data.data
        const editContent = BraftEditor.createEditorState(info.content)
        this.setState({info, editContent})
     }

     // 触发表单校验
     FormSubmit = () => {
        this.myRef.current.submit()
     }
    
     // 表单数据校验成功
     successData = (values) => {
      const htmlContent = this.state.editContent.toHTML()
      this.setState({info: {...this.state.info, content: htmlContent.toString(), ...values}}, () => {
       this.confrim()
      })
     }

     // 表单检验失败
     FormError = () => {
         message.error('数据错误，操作失败')
     }


      // 更新数据
      updateData = async () => {
          const res = await updateMedicalStory(this.state.info)
          if (res.code === 200) {
            message.success('更新数据成功')
            this.getDetails()
            this.setState({Look: true})
        } else {
         message.error('更新数据失败')
        }
      }

      // 增加数据
      addData = async () => {
        const res = await addMedicalStory(this.state.info)
       if (res.code === 200) {
           message.success('更新数据成功')
           this.setState({Look: true})
           this.back()
       } else {
        message.error('更新数据失败')
       }
      
      }

      // 返回上一级
      back = () => {
          this.props.history.goBack()
      }

      // 编辑
      Edit = () => {
        this.setState({Look: false, fpicture: this.state.fpicture})
        window.sessionStorage.setItem('Look', false)
      }

      // 返回编辑
      backLook = () => {
          if (this.state.id) {
            this.setState({Look: true})
            window.sessionStorage.setItem('Look', true)
          } else {
              this.back()
              this.setState({Look: true})
              window.sessionStorage.setItem('Look', true)
          }
      
      }

      // 确认
      confrim = () => {
          if (this.state.id) {
              this.updateData()
          } else {
              this.addData()
          }
      }

   // 图片上传成功
   InsertImage = async (params) => {
    const formdate = new FormData()
    formdate.set('file',params.file)
    const res = await upload(formdate)
    if (res.code === 200) {
      message.success('文件上传成功')
      params.success({
        url: res.data.url
      })

      // success(res.data.url)
    } else {
      message.error('文件上传成功')
    }
    
}

// 编辑器内容改变
handleEditorChange = (editContent) => {
  this.setState({ editContent })
}

    

  render() {

    const { info, Look, editContent } = this.state
    return (
        <div>
            {/* 编辑 */}
           
          {Look ? ( <Card style={{minHeight: '720px'}}>
              <div style={{display: 'flex', justifyContent: 'space-between'}}>
              <Button type="ghost" onClick={() => this.back()} className="backBtn">返回</Button>
              <Button className="editBtn"  onClick={() => {this.Edit()}}>编辑</Button>
              </div>
            <Form 
            ref={this.myRef} 
            onFinish={this.successData}
            onFinishFailed={this.FormError}>
                <div style={{display: 'flex'}}>
                <div style={{flex: 1, lineHeight: '72px' ,display: 'flex'}}>
                   <span  style={{fontSize: '18px', fontWeight: 'bold'}}>投稿人:</span>
                   <span className="textHd2">{info.contributors}</span>
               </div>
                <div style={{flex: 1, lineHeight: '72px',display: 'flex'}}>
                   <span  style={{fontSize: '18px', fontWeight: 'bold'}}>红医故事标题:</span>
                   <span className="textHd2">{info.name}</span>
               </div>  
                </div>
                <div  style={{display: 'flex'}}>
                <div style={{flex: 1, lineHeight: '72px',display: 'flex'}}>
                   <span  style={{fontSize: '18px', fontWeight: 'bold'}}>点赞数:</span>
                   <span className="textHd2">{info.likes}</span>
               </div>
               <div style={{flex: 1, lineHeight: '72px' ,display: 'flex'}}>
                   <span  style={{fontSize: '18px', fontWeight: 'bold'}}>阅读量:</span>
                   <span className="textHd2">{info.reading}</span>
               </div>
                </div>
                <div  style={{display: 'flex', padding: '24px'}}>
                   <span style={{fontSize: '18px', fontWeight: 'bold'}}>内容:</span>
                   <div className="braft-output-content" dangerouslySetInnerHTML={{__html:info.content}}></div>
                </div>
            </Form>
            </Card>) : (
               <Card style={{minHeight: '720px'}}>
                <Form 
                ref={this.myRef} 
                initialValues={info}
                onFinish={this.successData}
                onFinishFailed={this.FormError}>
                    <div style={{display: 'flex'}}>
                    <Form.Item   label="土投稿人"   style={{flex: 1}}  name="contributors"   rules={[{required: true,}]}>
                       <Input  style={{width: '320px'}} ></Input>
                   </Form.Item>
                    <Form.Item label="医学常识标题" name="name"   rules={[{required: true,}]}  style={{flex: 1}}>
                       <Input style={{width: '320px'}}></Input>
                   </Form.Item>
                    </div>
                    <div  style={{display: 'flex'}} >
                    </div>
                    <div  style={{display: 'flex'}}>
                   <Form.Item  label="内容" style={{flex: 1}} >
                      <Form.Item>
                      <BraftEditor
                    value={editContent}
                    onChange={this.handleEditorChange}
                    onSave={this.FormSubmit}
                    media={{ uploadFn: this.InsertImage }}
                />
                      </Form.Item>
                   </Form.Item>
                    </div>
                </Form>
                <div style={{display: 'flex', justifyContent: 'flex-end'}}>
             <Button className="editBtn"  onClick={() => {this.FormSubmit()}}>确认</Button>
              <Button type="ghost" onClick={() => this.backLook()} className="backBtn" style={{marginLeft: '32px'}}>取消</Button>
              </div>
                </Card>
          )}
            
            {/* 查看 */}
        </div>
    );
  }
}

export default MedicalDetail;